package sorted;

import java.util.Arrays;

public class S08_CountingSort {

    public static void main(String[] args) {
        int[] arr = {5,7,2,3,4,1,6,18,9,10,16,56,34,23,11,12,1,17,15};
        countingSort(arr);

        System.out.println("排序后的数组为："+ Arrays.toString(arr));
    }
    public static int[] countingSort(int[] arr) {
        int min = arr[0];
        int max = arr[0];

        for (int i : arr) {
            if (i < min) min = i;
            if (i > max) max = i;
        }
        int[] record = new int[max - min+1];

        for (int i : arr) {
            record[i-min]++;
        }

        int index = 0;
        for (int i = 0; i < record.length; i++) {
            int count = record[i];
            while (count-- > 0) {
                arr[index++] = i+min;
            }
        }

        return arr;
    }
}
